# 进行文件目录相关的操作
import os

"""读写文件"""
def readWriteFile():
    f = open("new_file.txt", "w")  # 创建并打开
    f.write("some text...")  # 在文件里写东西 会覆盖文件原有的内容
    f.close()  # 关闭

    # with方式打开 可以不需要手动close
    with open("new_file.txt", "w") as f:
        f.write("Hello")


"""读写目录 检查目录是否存在"""
def osTest():
    nowPath=os.getcwd()
    print(nowPath)
    print(os.listdir())
    os.makedirs('new',exist_ok=True)
    print(os.path.exists("new"))

    # 遍历目录
    path="D:\\迅雷下载\\常用软件"
    printDir(path)


"""遍历并打印目录中的文件"""
def printDir(path):
    for tmp in os.listdir(path):
        tmpPath = os.path.join(path,tmp)
        if(os.path.isdir(tmpPath)):
            printDir(tmpPath)
        else:
            print(tmpPath)


"""异常捕获测试"""
def tryTest():
    try:
        with open("List.py","r",encoding='utf-8') as file:
            # readlines可以读取整个文件
            # print(file.readlines())
            # read读取特定字符个数的函数
            print(file.read(5))
    except FileNotFoundError as e:
        print(e.filename+"读取出现异常")


if __name__ == '__main__':
    # readWriteFile()
     osTest()
    # tryTest()